//#define __DEBUG__
#define THIS_FILE "fn_taskHomed.sqf"
#include "x_setup.sqf"

__TRACE_1("_this","_this")
if (count _this < 2) exitWith {false};

private ["_grp", "_pos", "_list"];
PARAMS_2(_grp,_pos);

if (typeName _grp != "GROUP" || {typeName _pos != "ARRAY"}) exitWith {false};
_grp setBehaviour "SAFE";
_list = _pos call FUNC(getnearestbuilding);
if (count _list < 2 || {(_list select 1) <= 1}) exitWith { false };

__TRACE_1("Building","_list")

[_grp, _pos, _list] spawn {
	private ["_grp","_pos","_list","_max","_indices","_bldg","_wp","_units"];
	PARAMS_3(_grp,_pos,_list);
	_bldg = _list select 0;
	_indices = _list select 1;
	_max = ((count (units _grp)) min (_indices)) - 1;
	_units = (units _grp);
	_wp = _grp addWaypoint [getPos _bldg, 30];
	_wp setWaypointType "HOLD";
	for "_i" from _max to 0 step -1 do {
		private "_unit";
		_unit = (_units select _i);
		_units resize (count _units - 1);
		doStop _unit;
		sleep 1;
		_unit setPosATL (_bldg buildingPos _i);
		_unit forceSpeed 0;
		_unit setUnitPos "UP";
		sleep 1;
		_unit setVariable ["HOMED_TRG",(count (units _grp)) / 2];
		// Unlocks when a player fires nearby
		_unit addEventHandler ["FiredNear",{ if (isPlayer (_this select 1)) then { (_this select 0) forceSpeed -1; (_this select 0) setUnitPos "AUTO"; }}];
		// Unlocks when the unit fires
		_unit addEventHandler ["Fired",{ (_this select 0) forceSpeed -1; (_this select 0) setUnitPos "AUTO"; }];
		// Unlocks the last units of a group if it's group gets slaughtered
		_unit addEventHandler ["Killed",{ if (count (units (group(_this select 0))) <= ((_this select 0) getVariable ["HOMED_TRG",1])) then { { _x forceSpeed -1; _x setUnitPos "AUTO"; } foreach (units (group (_this select 0))) } }];
#ifdef __DEBUG__
		[format["homed_%1",_unit], getPosASL _unit,"ICON","ColorYellow",[0.7,0.7],"",0,"loc_Church"] call FUNC(CreateMarkerGlobal);
#endif
	};
	// Left over units are placed around the building
	{
		_x setVariable ["HOMED_TRG",(count (units _grp)) / 2];
		_pos = [getPos _bldg, 50] call FUNC(GetRanPointCircle);
		_x setPos _pos;
#ifdef __DEBUG__
		[format["homed_%1",_x], getPosASL _x,"ICON","ColorYellow",[0.7,0.7],"",0,"loc_Chapel"] call FUNC(CreateMarkerGlobal);
#endif
		_x addEventHandler ["Killed",{ if (count (units (group(_this select 0))) <= ((_this select 0) getVariable ["HOMED_TRG",1])) then { { _x forceSpeed -1; _x setUnitPos "AUTO"; doStop _x; } foreach (units (group (_this select 0))) } }];
	} foreach _units;

	__TRACE_1("End","_grp")
};
true